// **************************************************************
// Com ++ Framework by the C++ World
// Please report defects: mailto:compp@cplusplusworld.com
// Please visit: http://www.cplusplusworld.com/socketlibrary.html
// **************************************************************

#include <iostream>

#include "SysPlusPlus/syscall.h"
#include "ComPlusPlus/Thread.h"
#include "SysPlusPlus/ComException.h"
#include <signal.h>


/**
* Internal Method.
*/


void compp::Thread::InitPThr() {

  PThr_id = 0;

  PAttr = NULL;

  Arguments = NULL;
}



/**
* Constructor
*/
compp::Thread::Thread() {

  InitPThr();

}


/**
* Destructor
*/
compp::Thread::~Thread() {
}

/**
* Constructor. Accepts argument
*/
compp::Thread::Thread(void *arg) {

  InitPThr();
  
  Start ( arg );

}


/**
* Internal Method.
*/
static void *sfunc (void* v ) {

  compp::Thread * f = (compp::Thread *) v;
  
  f->StartThreadFunc();
  return NULL;
}


/**
* Internal Method.
*/
void * compp::Thread::StartThreadFunc( ) {

  Run ( Arguments );
  return NULL;
}

/**
* Starting Thread
*/

bool compp::Thread::Start ( void *arg ) {

  Arguments = arg;
  int i;
  i = syspp::Call::Pthread_create ( &PThr_id, NULL,  sfunc,  this ) ;

  if ( i != 0  ) {
	std::cout << "Thread cannot be created.\n";
	throw syspp::ComException ( "Cannot create thread." );
  }

  return true;
}


/**
* Wait until Thread has finished execution.
* value_ptr used for storage of return value.
* value_ptr is ignored, if it is NULL
*/
bool compp::Thread::Join ( void **value_ptr  ) {
int i;

  i = syspp::Call::Pthread_join ( PThr_id, value_ptr );
  return i ? false : true;

}
/**
* All Ressources are freed after termination of the 
* thread.
* Join () method is disable for this thread.
*/
bool compp::Thread::Detach ( ) {
int i;

  i = syspp::Call::Pthread_detach ( PThr_id );
  return i ? false : true;

}

/**
* Kill signal is sent to the thread.
*/
bool compp::Thread::Terminate ( ) {
  int j=0;

  pthread_exit ( &j );
  return true;
}


